// 接口环境
var local_proxy = ['', ''][0]
var api_robot = window.location.href.indexOf('.cn') > 0 ? "" : local_proxy
var api_host = {
    'robot': api_robot,
}

// js 给字符串String原型添加方法 借助正则表达式替换链接参数
String.prototype.replaceUrlParamOne = function (paramKey, newParamVal) {
    var regex = new RegExp('(' + paramKey + '=)[^&]*', 'g');
    return this.replace(regex, '$1' + newParamVal);
}

// 请求中转
function axios_request(config, callback) {
    var token = ''
    var url = config.url || ''
    var method = (config.method || 'get').toLowerCase()
    var data = config.data || {}
    var host = api_host[config.project || 'robot']
    if (method == 'post') {
        axios.post(host + url, data, {
            headers: {
                'token': token,
                'content-type': config.contentType || null,
            },
            onUploadProgress: config.onUploadProgress,
        }).then(function (response) {
            var rd = response && response.data || {}
            callback(rd)
        }).catch(function (error) {
            callback(error)
        });
    } else {
        axios.get(host + url, {
            params: data,
            headers: {'token': token,}
        }).then(function (response) {
            var rd = response && response.data || {}
            callback(rd)
        }).catch(function (error) {
            callback(error)
        })
    }
}

// axios 中的响应拦截器就可以获取到的
// 添加响应拦截器
axios.interceptors.response.use(
    function (response) {
        // 对响应数据做点什么
        var rd = response && response.data || {}
        if (rd.code == 401) {
            //
            // window.location.href = window.location.href.replaceUrlParamOne('token', '').replaceUrlParamOne('t', new Date().getTime())
        }
        return response;
    },
    function (error) {
        var _method = error.request._method
        var _url = error.request._url
        var status = error.response.status
        var errMsg = _method + ' ' + _url + ' ' + status
        console.error(errMsg)
        return Promise.reject(error);
    }
);